import { CONFIG } from '../config'
import { MessageType } from './constants.js'
import { WebSocketManager } from './core-manager.js'
import globalWSManager from './global-manager.js'

/**
 * 处理用户状态变更消息
 */
function handleUserStatusChange(message) {
	console.log('收到用户状态变更:', message)
	
	// 触发全局事件，让其他组件可以监听
	uni.$emit('userStatusChange', {
		userId: message.user_id,
		userName: message.user_name,
		isOnline: message.content === 'online'
	})
}

/**
 * 处理好友状态列表消息
 */
function handleFriendsStatus(message) {
	try {
		// 新的消息格式使用Data字段
		const friendsStatus = message.data?.friends || JSON.parse(message.content || '[]')
		console.log('收到好友状态列表:', friendsStatus)
		
		// 触发全局事件
		uni.$emit('friendsStatusUpdate', friendsStatus)
	} catch (error) {
		console.error('解析好友状态失败:', error)
	}
}

/**
 * 创建游戏房间 WebSocket 管理器
 */
export function createGameRoomManager(gameType, roomId, userId, userName, handlers = {}) {
  // 确保userId是字符串类型
  const userIdStr = String(userId || '');
  const wsUrl = `${CONFIG.WS_URL}/ws?userId=${userIdStr}&userName=${encodeURIComponent(userName || '')}&roomId=${roomId}&gameType=${gameType}`
  
  console.log('创建游戏房间管理器:', { gameType, roomId, userId: userIdStr, userName })
  console.log('WebSocket URL:', wsUrl)
  
  // 检查是否已有相同游戏房间的连接
  if (globalWSManager.hasConnection('gameRoom', roomId, gameType)) {
    const existingManager = globalWSManager.getConnection('gameRoom', roomId, gameType)
    console.log('已存在相同游戏房间的连接，复用现有连接')
    
    // 如果现有连接已连接，直接返回现有管理器
    if (existingManager && existingManager.getConnected()) {
      console.log('复用现有游戏房间连接')
      return existingManager
    }
  }
  
  const manager = new WebSocketManager({
    url: wsUrl,
    connectionType: 'gameRoom',
    roomId: roomId,
    gameType: gameType,
    onOpen: () => {
      console.log(`连接到${gameType}房间: ${roomId}`)
      
      // 发送加入房间消息
      const joinMessage = {
        type: MessageType.JOIN,
        user_id: userIdStr,
        user_name: userName,
        room_id: String(roomId),
        game_type: gameType,
        time: Math.floor(Date.now() / 1000)
      }
      manager.send(joinMessage)
      
      if (handlers.onOpen) {
        handlers.onOpen()
      }
    },
    onMessage: (message) => {
      console.log('收到游戏消息:', message)
      
      // 根据消息类型调用相应的处理器
      switch (message.type) {
        case MessageType.JOIN:
          if (handlers.onJoin) handlers.onJoin(message)
          break
        case MessageType.LEAVE:
          if (handlers.onLeave) handlers.onLeave(message)
          break
        case MessageType.READY:
        case MessageType.READY_CHANGED:
          if (handlers.onReady) handlers.onReady(message)
          break
        case MessageType.GAME_OP:
          if (handlers.onGameOp) handlers.onGameOp(message)
          break
        case MessageType.GAME_STATE:
          if (handlers.onGameState) handlers.onGameState(message)
          break
        case MessageType.GAME_START:
          if (handlers.onGameStart) handlers.onGameStart(message)
          break
        case MessageType.GAME_END:
          if (handlers.onGameEnd) handlers.onGameEnd(message)
          break
        case MessageType.USER_LIST_UPDATE:
          if (handlers.onUserListUpdate) handlers.onUserListUpdate(message)
          break
        case MessageType.ROOM_USER_COUNT:
          if (handlers.onRoomUserCount) handlers.onRoomUserCount(message)
          break
        case MessageType.SYSTEM:
          if (handlers.onSystem) handlers.onSystem(message)
          break
        default:
          console.log('未知消息类型:', message.type)
      }
    },
    onClose: (event) => {
      console.log('游戏房间连接关闭:', event)
      if (handlers.onClose) handlers.onClose(event)
    },
    onError: (error) => {
      console.error('游戏房间连接错误:', error)
      if (handlers.onError) handlers.onError(error)
    }
  })

  return manager
}

/**
 * 创建聊天房间 WebSocket 管理器
 * 聊天房间需要预先的房间ID
 */
export function createChatRoomManager(roomId, userId, userName, handlers = {}) {
  // 确保userId是字符串类型
  const userIdStr = String(userId || '');
  const wsUrl = `${CONFIG.WS_URL}/ws?userId=${userIdStr}&userName=${encodeURIComponent(userName || '')}&roomId=${roomId}`
  
  console.log('创建聊天房间管理器:', { roomId, userId: userIdStr, userName })
  console.log('WebSocket URL:', wsUrl)
  
  // 检查是否已有相同聊天房间的连接
  if (globalWSManager.hasConnection('chatRoom', roomId)) {
    const existingManager = globalWSManager.getConnection('chatRoom', roomId)
    console.log('已存在相同聊天房间的连接，复用现有连接')
    
    // 如果现有连接已连接，直接返回现有管理器
    if (existingManager && existingManager.getConnected()) {
      console.log('复用现有聊天房间连接')
      return existingManager
    }
  }
  
  const manager = new WebSocketManager({
    url: wsUrl,
    connectionType: 'chatRoom',
    roomId: roomId,
    onOpen: () => {
      console.log(`连接到聊天房间: ${roomId}`)
      
      if (handlers.onOpen) {
        handlers.onOpen()
      }
    },
    onMessage: (message) => {
      console.log('收到聊天消息:', message)
      
      // 根据消息类型调用相应的处理器
      switch (message.type) {
        case MessageType.JOIN:
          if (handlers.onJoin) handlers.onJoin(message)
          break
        case MessageType.LEAVE:
          if (handlers.onLeave) handlers.onLeave(message)
          break
        case MessageType.TEXT:
          if (handlers.onText) handlers.onText(message)
          break
        case MessageType.READ:
          if (handlers.onRead) handlers.onRead(message)
          break
        case MessageType.USER_LIST_UPDATE:
          if (handlers.onUserListUpdate) handlers.onUserListUpdate(message)
          break
        case MessageType.ROOM_USER_COUNT:
          if (handlers.onRoomUserCount) handlers.onRoomUserCount(message)
          break
        case MessageType.SYSTEM:
          if (handlers.onSystem) handlers.onSystem(message)
          break
        default:
          console.log('未知消息类型:', message.type)
      }
    },
    onClose: (event) => {
      console.log('聊天房间连接关闭:', event)
      if (handlers.onClose) handlers.onClose(event)
    },
    onError: (error) => {
      console.error('聊天房间连接错误:', error)
      if (handlers.onError) handlers.onError(error)
    }
  })

  return manager
}

/**
 * 创建房间列表 WebSocket 管理器
 */
export function createRoomListManager(userId, userName, handlers = {}) {
  const wsUrl = `${CONFIG.WS_URL}/ws?userId=${userId}&userName=${encodeURIComponent(userName)}`
  
  console.log('创建房间列表管理器:', { userId, userName })
  console.log('WebSocket URL:', wsUrl)
  
  // 检查是否已有房间列表连接
  if (globalWSManager.hasConnection('roomList')) {
    const existingManager = globalWSManager.getConnection('roomList')
    console.log('已存在房间列表连接，复用现有连接')
    
    // 如果现有连接已连接，直接返回现有管理器
    if (existingManager && existingManager.getConnected()) {
      console.log('复用现有房间列表连接')
      return existingManager
    }
  }
  
  const manager = new WebSocketManager({
    url: wsUrl,
    connectionType: 'roomList',
    onOpen: () => {
      console.log('连接到房间列表服务')
      
      if (handlers.onOpen) {
        handlers.onOpen()
      }
    },
    onMessage: (message) => {
      console.log('收到房间列表消息:', message)
      
      if (handlers.onMessage) {
        handlers.onMessage(message)
      }
    },
    onClose: (event) => {
      console.log('房间列表连接关闭:', event)
      if (handlers.onClose) handlers.onClose(event)
    },
    onError: (error) => {
      console.error('房间列表连接错误:', error)
      if (handlers.onError) handlers.onError(error)
    }
  })

  return manager
} 